package com.wlf.mq.send;

import com.wlf.entity.User;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

@Component
public class DirectMsgSender {

    @Value("${ut.order.queue}")
    private String utOrderQueue;

    @Value("${ut.print.queue}")
    private String printDirectQueue;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${utruck.config.api.max-size}")
    private Integer maxSize;

    @Value("${utruck.config.api.order.queue}")
    private String apiOrderQueue;

    /**
     * 发送消息
     * @param message 消息体
     * @param index 队列号
     */
    public void send(String message, int index) {
        String format = MessageFormat.format(utOrderQueue, index);
        rabbitTemplate.convertAndSend(format, message);
    }

    /**
     * 发送消息
     * @param message 消息体
     * @param index 队列号
     */
    public void sendPrint(String message, int index) {
        String format = MessageFormat.format(printDirectQueue, index);
        rabbitTemplate.convertAndSend(format, message);
    }


    /**
     * 发送用户注册认证校验消息
     * @param message 消息体
     * @param size 队列大小
     */
    public User sendOrderAuthQueue(String message,String id,int size) {
        int index = calcQueueIndex();
        String format = MessageFormat.format(apiOrderQueue, index);
        User user =com.alibaba.fastjson.JSONObject.parseObject(message, User.class);
        user.setQueue(format);
        rabbitTemplate.convertAndSend(format, com.alibaba.fastjson.JSONObject.toJSONString(user));
        return user;
    }

    /**
     * 计算存储队列index
     * @param
     * @return
     */
    private int calcQueueIndex() {
        return (int)(Math.random() * maxSize);
    }

}
